package com.shuoyue.ffmpegvideocut.ffmpegutil;

import com.shuoyue.ffmpegvideocut.controller.oss.MinioConfig;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Component
public class FfmpegCmdHls4M3u8EncUtil {
    //加密文件路径，如：enc.key、enc.keyinfo、m3u8文件、ts文件等
    private String ENC_DIRECTORY = "";

    //执行成功0,失败1
    public static int CODE_SUCCESS = 0;
    public static int CODE_FAIL = 1;

    // MP4 --> HLS m3u8 AES128 加密（//注意绝对路径///）
    //视频路径：I:\\test-ffmpeg\\荣耀视频测试.mp4
    //$encInfoPath、$encPath是需要替换的ENC_DIRECTORY文件路径
    private String cmd_enc = " -y -i" +
            " $sourceVideoPath" +
            " -hls_time" +
            " $fragmentSeconds" +
            " -hls_key_info_file" +
            " $encInfoPath" +
            " -hls_playlist_type vod -hls_segment_filename" +
            " $encPath" + File.separator + "$fileName_$timeSeconds_%3d.ts" +
            " $encPath" + File.separator + "video.m3u8 ";


    /**
     * 第一步：创建enc.keyinfo文件
     * 第二步：HLS m3u8 AES128 加密
     *
     * @param savePath
     * @param videoPath
     * @param minioConfig "http://localhost:8000/enc.key"
     * @param timeSeconds
     * @throws
     * @param: @param args
     * @return: void
     */
    public boolean excudCmd(String savePath, String videoPath, MinioConfig minioConfig, String timeSeconds,String fileName) {
        this.ENC_DIRECTORY = savePath;
        cmd_enc = cmd_enc.replace("$sourceVideoPath", videoPath)
                .replace("$fragmentSeconds", timeSeconds)
                .replace("$fileName", fileName)
                .replace("$timeSecond", timeSeconds);

        int result = encode(minioConfig);
        //code=0表示正常
        System.out.println(String.format("获取最终执行结果:%s", result == CODE_SUCCESS ? "成功！" : "失败！"));
        if (result == CODE_SUCCESS) {
            return true;
        }
        return false;
    }

    private int encode(MinioConfig minioConfig) {
        Integer codeTmp = cmdExecut(cmd_enc.replace("$encInfoPath", minioConfig.getM3u8KeyInfoUrlPath()).replace("$encPath", ENC_DIRECTORY));
        System.out.println(" HLS m3u8 AES128 加密,成功！");
        return codeTmp;
    }

    /**
     * @throws
     * @Description: (执行ffmpeg自定义命令)
     * @param: @param cmdStr
     * @param: @return
     * @return: Integer
     */
    public Integer cmdExecut(String cmdStr) {
        //code=0表示正常
        Integer code = null;
        FfmpegCmd ffmpegCmd = new FfmpegCmd();
        /**
         * 错误流
         */
        InputStream errorStream = null;
        try {
            //destroyOnRuntimeShutdown表示是否立即关闭Runtime
            //如果ffmpeg命令需要长时间执行，destroyOnRuntimeShutdown = false

            //openIOStreams表示是不是需要打开输入输出流:
            //	       inputStream = processWrapper.getInputStream();
            //	       outputStream = processWrapper.getOutputStream();
            //	       errorStream = processWrapper.getErrorStream();
            ffmpegCmd.execute(false, true, cmdStr);
            errorStream = ffmpegCmd.getErrorStream();

            //打印过程
            int len = 0;
            while ((len = errorStream.read()) != -1) {
                System.out.print((char) len);
            }

            //code=0表示正常
            code = ffmpegCmd.getProcessExitCode();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            ffmpegCmd.close();
        }
        //返回
        return code;
    }

}

